package org.martyn.danbooru;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.martyn.danbooru.error.DanbooruException;
import org.martyn.danbooru.http.HttpApi;
import org.martyn.danbooru.parsers.xml.PostParser;
import org.martyn.danbooru.types.groups.PostGroup;
import org.martyn.danbooru.utils.TagUtils;
import org.xml.sax.SAXException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Danbooru
{
	private static final String URN_API_XML_EXTENTION = ".xml";
	private static final String URN_API_JSON_EXTENTION = ".json";

	private static final String URN_PROTOCOL = "http://";
	
	private static final String URN_API_POST = "/post/index";
	private static final String URN_API_TAG = "/tag/index";
	

	private DanbooruConnectSettings danbooruConnectSettings;

	private DefaultHttpClient httpClient;
	private HttpApi httpApi;

	public Danbooru(DanbooruConnectSettings danbooruConnectSettings)
	{
		this.danbooruConnectSettings = danbooruConnectSettings;

		httpClient = HttpApi.createHttpClient();
		httpApi = new HttpApi(httpClient, "Mozilla/5.0");
	}

	public boolean isDanbooru()
	{
		// TODO: checken of de site echt bestaat

		return true;
	}

	public PostGroup listPosts(int postPerPage, int currentPage, String... tags)
			throws IOException, ParserConfigurationException, SAXException,
			DanbooruException
	{
		HttpGet httpGet = httpApi.createHttpGet(
				FullPath(URN_API_POST),
				new BasicNameValuePair("limit", String.valueOf(postPerPage)),
				new BasicNameValuePair("page", String.valueOf(currentPage)),
				new BasicNameValuePair("tags", TagUtils.ParseTagsForRequest(tags)));

		InputStream inputStream = httpApi.executeHttpRequest(httpGet);

		PostGroup postGroup = new PostParser().Parse(inputStream);

		postGroup.setPostPerPage(20);
		postGroup.setCurrentPage(currentPage);

		return postGroup;
	}

	public Bitmap picture(String url) throws DanbooruException, IOException
	{
		HttpGet httpGet = httpApi.createHttpGet(url, null);

		InputStream inputStream = httpApi.executeHttpRequest(httpGet);

		return BitmapFactory.decodeStream(inputStream);
	}

	private String FullPath(String urn)
	{
		return URN_PROTOCOL + danbooruConnectSettings.hostName + urn + Extention();
	}

	private String Extention()
	{
		if (danbooruConnectSettings.danbooruParseType.equals(DanbooruConnectSettings.DANBOORU_PARSE_TYPE_XML))
		{
			return URN_API_XML_EXTENTION;
		}
		else
		{
			return URN_API_JSON_EXTENTION;
		}
	}

}
